package org.alex.nettychat.netty.custom.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.alex.nettychat.netty.custom.protocol.JoinGroupRequestPacket;
import org.alex.nettychat.netty.custom.protocol.JoinGroupResponsePacket;
import org.alex.nettychat.netty.custom.utils.SessionUtil;


/**
 * 加入群里请求
 *
 * @author : alex
 */
public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket requestPacket) throws Exception {
        // 获取群对应的ChannelGroup 然后加入group
        Integer groupId = requestPacket.getGroupId();

        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        channelGroup.add(ctx.channel());

        // 构造加群响应
        JoinGroupResponsePacket responsePacket = new JoinGroupResponsePacket();
        responsePacket.setSuccess(true);
        responsePacket.setUserName(SessionUtil.getSession(ctx.channel()).getUserName());
        responsePacket.setGroupId(groupId);

        // 为每个channel发送消息
        channelGroup.writeAndFlush(responsePacket);
    }
}
